package br.gendi.rcp;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;

import br.gendi.beans.BaseGenomica;
import br.gendi.core.Conectividade;
import br.gendi.core.Parser;
import br.gendi.core.Util;
import br.gendi.dialog.ConfiguracoesBases;
import br.gendi.dialog.Visualizador;

public class View extends ViewPart {

	private Label label = null;
	private Text text = null;
	private Button button = null;
	private Label label1 = null;
	private Text textArea = null;
	private Button button1 = null;
	private Button button2 = null;
	private Visualizador v = null;
	private Shell shell = null;

	public static final String ID = "br.gendi.rcp.view";

	public void createPartControl(final Composite parent) {
		shell = parent.getShell();
		GridData gridData6 = new GridData();
		gridData6.horizontalAlignment = GridData.BEGINNING;
		gridData6.verticalAlignment = GridData.CENTER;
		GridData gridData5 = new GridData();
		gridData5.horizontalAlignment = GridData.BEGINNING;
		gridData5.verticalAlignment = GridData.BEGINNING;
		GridData gridData4 = new GridData();
		gridData4.horizontalAlignment = GridData.FILL;
		gridData4.verticalAlignment = GridData.BEGINNING;
		GridData gridData3 = new GridData();
		gridData3.horizontalAlignment = GridData.FILL;
		gridData3.verticalAlignment = GridData.BEGINNING;
		GridData gridData2 = new GridData();
		gridData2.grabExcessHorizontalSpace = true;
		gridData2.verticalAlignment = GridData.CENTER;
		gridData2.horizontalAlignment = GridData.FILL;
		GridData gridData1 = new GridData();
		gridData1.grabExcessHorizontalSpace = true;
		gridData1.verticalAlignment = GridData.FILL;
		gridData1.grabExcessVerticalSpace = true;
		gridData1.horizontalAlignment = GridData.FILL;
		GridData gridData = new GridData();
		gridData.verticalAlignment = GridData.CENTER;
		gridData.horizontalSpan = 2;
		gridData.horizontalAlignment = GridData.FILL;
		GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 4;
		label = new Label(parent, SWT.NONE);
		label.setText("Nova base genômica:");
		label.setLayoutData(gridData6);
		text = new Text(parent, SWT.BORDER);
		text.setLayoutData(gridData2);
		text.setText("http://www.cbs.dtu.dk/services/NetMHC");
		button = new Button(parent, SWT.NONE);
		button.setText("Adicionar Base");
		button.setImage(new Image(shell.getDisplay(), getClass().getResourceAsStream("/images/addsite.png")));
		button.setLayoutData(gridData);
		label1 = new Label(parent, SWT.NONE);
		label1.setText("Busca:");
		label1.setLayoutData(gridData5);
		textArea = new Text(parent, SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER);
		textArea.setLayoutData(gridData1);
		textArea.setText("ASTPGHTIIYEAVCLHNDRTTIP");
		textArea.setFont(new Font(parent.getDisplay(),"courier new",9 , SWT.NONE));
		button1 = new Button(parent, SWT.NONE);
		button1.setText("Buscar");
		button1.setImage(new Image(shell.getDisplay(), getClass().getResourceAsStream("/images/stock-search.png")));
		button1.setLayoutData(gridData3);
		button2 = new Button(parent, SWT.NONE);
		button2.setText("Carregar arquivo");
		button2.setLayoutData(gridData4);
		button2.setImage(new Image(shell.getDisplay(), getClass().getResourceAsStream("/images/gnome-fs-directory.png")));
		parent.setLayout(gridLayout);
		button1.addSelectionListener(new SelectionListener() {

			public void widgetDefaultSelected(SelectionEvent e) {

			}

			public void widgetSelected(SelectionEvent e) {
				final String retorno = textArea.getText();
				if (retorno.length() == 0)
					return;
				try{
					v = new Visualizador();

					if (true==true) {
						//TODO: usar configurações salvas.
						/*
						ArrayList<BaseGenomica> bases = Util.basesConfiguradas();
						for (int i=0; i<bases.size(); i++) {
							BaseGenomica base = bases.get(i);
							String d = Conectividade.retornarHTMLGerar(retorno, base);
							v.adicionar(base.getTitulo(), d);
						}
						*/
					}
					
					Thread operationThread2 = new Thread() {
						public void run() {
							String d = null;
							try {
								d = Conectividade.retornarHTML(retorno);
							} catch (Exception e) {  e.printStackTrace(); }
							final String retD = d;

							shell.getDisplay().asyncExec(new Runnable() {
								public void run() {
									v.adicionarSite("NetMHC", retD);
								}
							});
						}
					};
					operationThread2.start();

					Thread operationThread = new Thread() {
						public void run() {

							String d = null;
							try {
								d = Conectividade.retornarHTMLEpijen(retorno);
							} catch (Exception e) {
								e.printStackTrace();
							}
							final String retD = d;
							
							shell.getDisplay().asyncExec(new Runnable() {
								public void run() {
									v.adicionarSiteHTML("EpiJen", retD);
								}
							});
						}
					};
					operationThread.start();

				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		});

		button2.addSelectionListener(new SelectionListener() {

			public void widgetDefaultSelected(SelectionEvent arg0) {

			}

			public void widgetSelected(SelectionEvent arg0) {

				FileDialog f = new FileDialog(new Shell());
				final String retorno = f.open();

				Thread operationThread = new Thread() {
					public void run() {
						final StringBuffer sb = new StringBuffer();

						if (retorno != null) {
							FileReader fReader = null;
							try {
								fReader = new FileReader(retorno);
							} catch (FileNotFoundException e) {
								e.printStackTrace();
							}
							int c;
							try {
								while ((c = fReader.read()) != -1) {
									sb.append((char)c);
								}
							} catch (IOException e) {
								e.printStackTrace();
							}
						}

						shell.getDisplay().asyncExec(new Runnable() {
							public void run() {
								textArea.setText(sb.toString());
							}
						});
					}
				};
				operationThread.start();
				writeToStatusLine("Arquivo importado com sucesso.");
			}
		});

		button.addSelectionListener(new SelectionListener() {
			public void widgetDefaultSelected(SelectionEvent arg0) {

			}

			public void widgetSelected(SelectionEvent arg0) {
				final String texto = text.getText();

				if (texto.length() == 0) {
					MessageDialog.openError(shell, "GENDI: Erro", "Sem site para adicionar.");
					return;
				}
				try {
					new URL(texto);
				} catch (MalformedURLException e) {
					MessageDialog.openError(shell, "GENDI: Erro", "Endereço não é valido: " + texto + "\n\n"+e.toString());
					return;
				}
				Thread operationThread = new Thread() {
					public void run() {
						final BaseGenomica b = Parser.parseSite(texto);

						shell.getDisplay().asyncExec(new Runnable() {
							public void run() {
								ConfiguracoesBases c = new ConfiguracoesBases(b);
							}
						});
					}
				};
				operationThread.start();
				writeToStatusLine("Pesquisa iniciada.");
			}
		});
	}

	@Override
	public void setFocus() {
	}

	private void writeToStatusLine(String aMessage) {
		final String msg = aMessage;

		getViewSite().getShell().getDisplay().asyncExec (new Runnable () {
			public void run () {
				getViewSite().getActionBars().getStatusLineManager().setMessage(msg);
			}
		});
	}

}
